const express = require("express");
const app = express();
// const bodyParser = require("body-parser");
// 自定义实现body-parser
let bodyParser = {};
// 处理表单数据
bodyParser.urlencoded = function () {
  return (req, res, next) => {
      console.log(req.headers["content-type"]);

    if (req.headers["content-type"] === "application/x-www-form-urlencoded") {
      let arr = [];
      req.on("data", function (chunk) {
        arr.push(chunk);
      });
      req.on("end", function () {
        req.body = require("querystring").parse(Buffer.concat(arr).toString());
        next();
      });
    } else {
      next();
    }
  };
};
// 处理json数据
bodyParser.json = function () {
  return (req, res, next) => {
    if (req.headers["content-type"] === "application/json") {
      let arr = [];
      req.on("data", function (chunk) {
        arr.push(chunk);
      });
      req.on("end", function () {
        req.body = JSON.parse(Buffer.concat(arr).toString());
        next();
      });
    } else {
      next();
    }
  };
};

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.post("/api", function (req, res) {
  res.send(req.body);
});

app.listen(3000);
